'use strict';

var mongoose = require('../db');
var formatDate = require('../helpers/format-date');

var moneySchema = mongoose.Schema({
    currency: {
        type: String,
        required:true
    },
    date: {
        type: Date,
        'default': Date.now
    },
    category: {
        type: String,
        required:true
    },
    event: String,
    note: String,
    money: {
        type: Number,
        required: true
    },
    order: Number
});

moneySchema.index({ date: -1, order: -1 });
var Money = mongoose.model('money', moneySchema);

var cachedData;

function filterCategories(data) {
    var list = [],
        filter = [];
    Object.keys(data).forEach(function(key) {
        var category = data[key].category;
        if (list.lastIndexOf(category) === -1) {
            list.push(category);

            var parent = category.split('.')[0];

            if (filter.lastIndexOf(parent) === -1) {
                filter.push(parent);
            }
        }
    });

    list = list.sort();
    filter = filter.sort();

    return {
        list: list,
        filter: filter
    };
}

function filterEvents(data) {
    var result = [];
    Object.keys(data).forEach(function(key) {
        var event = data[key].event;
        if (result.lastIndexOf(event) === -1) {
            result.push(event);
        }
    });

    return result.sort().reverse();
}

function getInfo(cb) {

    if (cachedData) {
        console.log('get data from cache');
        return cb(null, cachedData);
    }

    Money.find().sort({
        date: -1,
        order: -1
    }).exec(function(err, data) {
        console.log('found');
        if (err) {
            return cb(err);
        }

        var info = {
            categories: filterCategories(data),
            events: filterEvents(data)
        };

        cachedData = {
            data: data,
            info: info
        };

        setTimeout(function() {
            cachedData = null;
        }, 5 * 60 * 1000);

        cb(null, cachedData);
    });
}

function insert(data) {
    return function(callback) {
        data.currency = data.currency || 'CNY';
        var money = new Money(data);
        money.order = 1;

        if (money.moeny === null || money.money === undefined) {
            throw new Error('moeny value should be number');
        }

        getInfo(function(err, result) {
            var lastData = result.data[0];

            if (formatDate(lastData.date) === formatDate(money.date)) {
                money.order = lastData.order + 1;
            }

            result.data.unshift(money);

            money.save(function(err) {
                callback(err, money);
            });
        });
    };
}
module.exports = Money;
Money.getInfo = getInfo;
Money.insert = insert;
